import { mallApi } from '/api/mall'
import { $event } from '/utils'

Page({
  data: {
    list: [] as any,
    isLastpage: false,
    brand: '' as any,
    id: 0,
    show: false,
    /** 商城列表跳转过来的 */
    mall: false,
    keyword: '',
  },
  async onLoad({ id = 0 }) {
    if (id) {
      this.setData({
        mall: true,
      })
    }
    const pages = getCurrentPages()
    const lastpage = pages[pages.length - 2]
    this.setData({
      id: lastpage.data.brandId,
    })
    await this.getData()
  },
  onPullDownRefresh() {
    this.getData()
  },
  async getData(more = false) {
    wx.showLoading({ title: '加载中...' })
    const list = await mallApi.getBrands({
      offset: more ? this.data.list.length : 0,
      limit: 15,
      keyword: this.data.keyword,
    })
    this.setData({
      list: more ? [...this.data.list, ...list] : list,
      isLastpage: list.length < 15,
      show: true,
    })
    wx.hideLoading()
  },
  onReachBottom() {
    const {
      data: { isLastpage },
    } = this
    if (isLastpage) {
      wx.showToast({
        title: '已没有更多',
        icon: 'none',
      })
      return
    }
    this.getData(true)
  },
  /** 输入搜索关键字 */
  onInputKeyword(e: WechatMiniprogram.Input) {
    const {
      detail: { value },
    } = e
    this.setData({
      keyword: value,
    })
  },
  /** 搜索 */
  search() {
    this.getData()
  },
  /** 选择广告 */
  choose(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { item },
      },
    } = e
    this.setData({
      brand: item,
    })
    const {
      data: { mall },
    } = this
    const pages = getCurrentPages()
    const lastpage = pages[pages.length - 2]
    const makes = lastpage.data.makes
    if (mall) {
      let makeIndex = -1
      makes.forEach((i: any, index: number) => {
        if (item.id == i.id) {
          makeIndex = index
        }
      })
      if (makeIndex < 0) {
        /** 品牌列表没有这个品牌 */
        makes.splice(16, 1, item)
        lastpage.setData({
          makes,
        })
      }
      lastpage.setData({
        makeIndex: makeIndex < 0 ? 16 : makeIndex,
        brandId: item.id,
      })
      $event.emit('after:chooseBrands')
    } else {
      lastpage.setData({
        brand: item,
        brandId: item.id,
      })
    }
    wx.navigateBack({
      delta: 1,
    })
  },
})
